#include "ImageLabelOutputFilter.h"
#include <qdebug.h>
#include <memory>
#include <QPainter>
#include <XnCppWrapper.h>
#include <QApplication>
#include <QDesktopWidget>
#include "support.h"

ImageLabelOutputFilter::ImageLabelOutputFilter(QWidget *parent)
	: QWidget(parent), Filter(1, 0)
{
	this->setMouseTracking(true);
	QObject::connect(this, SIGNAL(done()), this, SLOT(update()));
	//setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
	setMinimumSize(XN_VGA_X_RES, XN_VGA_Y_RES);
	setMaximumSize(2*XN_VGA_X_RES, 2*XN_VGA_Y_RES);
	updateGeometry();
}

ImageLabelOutputFilter::~ImageLabelOutputFilter()
{
}

void ImageLabelOutputFilter::Process()
{
	imageMutex.lock();
	image = MatToQImage(*inputs[0]);
	if (imageSize.width() < image.size().width() || imageSize.height() < image.size().height()) {
		imageSize = image.size();
	}

	imageMutex.unlock();
	emit done();
}

void ImageLabelOutputFilter::ProcessInvalid()
{
	Process();
}

void ImageLabelOutputFilter::paintEvent(QPaintEvent *event)
{
	imageMutex.lock();
	if (!image.isNull())
	{
		//setMinimumSize(imageSize);
		//updateGeometry();
		QPainter painter(this);

		double widgetRatio = (double)size().width() / (double)size().height();
		double imageRatio = (double)imageSize.width() / (double)imageSize.height();
		
		QRect imageRect;

		if (widgetRatio == imageRatio)
		{
			imageRect = QRect(0, 0, width(), height());
		}
		else if (widgetRatio > imageRatio)
		{
			double scale = (double) height() / (double) imageSize.height();
			imageRect = QRect(0, 0, scale * imageSize.width(), scale * imageSize.height());
		} else
		{
			double scale = (double) width() / (double) imageSize.width();
			imageRect = QRect(0, 0, scale * imageSize.width(), scale * imageSize.height());
		}

		painter.drawImage(imageRect, image);
	}
	imageMutex.unlock();
}

void ImageLabelOutputFilter::closeEvent(QCloseEvent *evt)
{
	emit closeWindow();
}

QWidget *ImageLabelOutputFilter::GetOutputWidget()
{
	return this;
}
